package com.cold.demo.webflux.exh;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class CommonWebExceptionHandler implements org.springframework.web.server.WebExceptionHandler {

    private Logger log = LoggerFactory.getLogger(CommonWebExceptionHandler.class);

    /**
     * 用于处理来自 WebFilter 链和 WebHandler 的异常
     * 如果异常被@ExceptionHandler处理了，那么将不会由此处理
     *
     * @param exchange
     * @param ex
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error("发生了更加底层的异常...");
        ex.printStackTrace();
        exchange.getResponse().setStatusCode(HttpStatus.OK);
        byte[]     bytes = ("ErrorLogHandler: " + ex.getMessage()).getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap  = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(wrap));
    }




}
